package com.umeox.sdk_ring.scan

import android.annotation.SuppressLint
import com.umeox.sdk_ring.RingScanCallback
import com.umeox.sdk_ring.UMRingSdk
import com.umeox.sdk_ring.UMScanResult
import no.nordicsemi.android.support.v18.scanner.*
import java.util.ArrayList

class RingDirectScanner(
    private val obj: Any,
    private val call: RingScanCallback,
    private val deviceFilterNames: List<String>
) {
    companion object {
        private const val TAG = "RingScanner"
    }

    private val scanCallback: ScanCallback = object : ScanCallback() {
        @SuppressLint("NewApi")
        override fun onBatchScanResults(results: MutableList<ScanResult>) {
            super.onBatchScanResults(results)
            results.forEach { result ->
                call.onScanResult(UMScanResult(result.device, result.rssi))
            }
        }
    }

    private var settings: ScanSettings = ScanSettings.Builder()
        .setLegacy(false)
        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
        .setReportDelay(1000)
        .setUseHardwareBatchingIfSupported(false) //默认为true，表示如果他们支持硬件分流批处理的话，使用硬件分流批处理;false表示兼容机制
        .build()

    private val filters: MutableList<ScanFilter> = ArrayList()

    private var isScanning = false

    private val mScanner = BluetoothLeScannerCompat.getScanner()

    /**
     * 开始扫描
     */
    fun startScan() {
        UMRingSdk.log(TAG, "请求开始扫描 isScanning = $isScanning   $obj")
        if (isScanning) return
        isScanning = true
        UMRingSdk.log(TAG, "@${hashCode()} 开始扫描   $obj")
        mScanner.stopScan(scanCallback)

        for (deviceFilterName in deviceFilterNames) {
            filters.add(ScanFilter.Builder().setDeviceName(deviceFilterName).build())
        }
        mScanner.startScan(filters, settings, scanCallback)
    }

    /**
     * 停止扫描
     */
    fun stopScan() {
        UMRingSdk.log(TAG, "请求停止扫描 isScanning = $isScanning   $obj")
        if (!isScanning) return
        isScanning = false
        UMRingSdk.log(TAG, "@${hashCode()} 暂停扫描   $obj")
        mScanner.stopScan(scanCallback)
    }
}